var Regions = new Array();
var RegionValues = new Array();
var Cities = new Array();
var CityValues = new Array();
var CityRegions = new Array();
var num_regions = new Array();
var num_cities = new Array();

var Areas = new Array();
var numAreas = 0;
var isChanging = false;
var doUpdateCountry = new Array();
var doUpdateRegion = new Array()
var doUpdateCity = new Array();

if (window.addEventListener){
      window.addEventListener('load', InitForms, false);
}else if (window.attachEvent){
    window.attachEvent('onload', InitForms);
}else {
     if ( window.onload != null ) {
          var _onload = window.onload;
          window.onload = function ( e ) {
            _onload(e);
            InitForms();
          };
    } else
          window.onload = InitForms;
}
function AddOption(sel, text, value)
{
    var el = document.createElement('option');
    el.text = text;
    el.value = value;
    try {
        sel.add(el, null);
    } catch (e)
    {
        sel.add(el);
    }

}

function InitForms()
{
	for (var j = 0; j < numAreas; j++) {
		var s1 = document.getElementById("Country" + Areas[j]);
		s1.remove(0);
	    for (var i = 0; i < num_countries; i++) {
	        AddOption(s1, Countries[i], CountryValues[i]);
	    }
	    s1.onchange = function() { eval("changeCountry(this, true)"); }
	    document.getElementById("Region" + Areas[j]).onchange = function() { eval("changeRegion(this, true)"); }
	    document.getElementById("City" + Areas[j]).onchange = function() { eval("changeCity(this, true)"); }
        document.getElementById("City" + Areas[j]).ondblclick = function() { eval("changeCity(this, true)"); }
        if (doUpdateCountry[Areas[j]] > 0) {
        	var c =	document.getElementById("Country" + Areas[j]);
    		c.value = doUpdateCountry[Areas[j]];
    		changeCountry(c, false);
        }
	}
}

function changeCountry(element, usreinit)
{
	var postfix = element.id;
	postfix=postfix.substr(7);
    var s1 = document.getElementById("Country" + postfix);
    var sr = document.getElementById("Region" + postfix);
    var sc = document.getElementById("City" + postfix);
    if (typeof onChangeCountry != 'undefined') onChangeCountry(postfix, usreinit);
    if (s1.value > 0) {
    
	    s1.options[s1.selectedIndex].text += '  (Загрузка...)';
	    s1.disabled=true;
	
	    var url = "getcountry?cid=" + s1.value;
	    SendRequest( url, function(xmlDom) {
	    	UpdateCountry(xmlDom, postfix);
	    });
    } else {
    	var xmlDoc;
        if (window.DOMParser) {
            var parser=new DOMParser();
            xmlDoc=parser.parseFromString(xmlhttp.responseText,"text/xml");
        } else // Internet Explorer
        {
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async="false";
        }
    	UpdateCountry(xmlDoc,postfix);
    }
}

function UpdateCountry(xmlDom, postfix)
{
    Regions[postfix]=new Array();
    RegionValues[postfix]=new Array();
    Cities[postfix]=new Array();
    CityValues[postfix]=new Array();
    CityRegions[postfix]=new Array();
    
    if (xmlDom.getElementsByTagName('String').length > 0) {
    	alert(xmlDom.getElementsByTagName('String')[0].childNodes[0].nodeValue);
    	return;
    }

    var s1 = document.getElementById("Country" + postfix);
    var sr = document.getElementById("Region" + postfix);
    var sc = document.getElementById("City" + postfix);
    s1.disabled=false;
    if (xmlDom.getElementsByTagName("com.transcargo.geo.Country").length > 0) {
	    var country = xmlDom.getElementsByTagName("com.transcargo.geo.Country")[0].childNodes;
	    var countryid = 0;
	    var countryname = '';
	    for (var j = 0; j < country.length; j++) {
	    	if (country[j].tagName == 'Id') countryid = country[j].childNodes[0].nodeValue;
	    	if (country[j].tagName == 'name') countryname = country[j].childNodes[0].nodeValue;
	    }
	    for (j = 0; j < s1.options.length; j++) {
	    	if (s1.options[j].value == countryid) s1.options[j].text = countryname;
	    }
	
	    
	    sr.innerHTML = '';
	    sc.innerHTML = '';
	    var regions = xmlDom.getElementsByTagName("com.transcargo.geo.Region");
	    for (var i = 0; i < regions.length; i++) {
	        var region = regions[i];
	        var name = region.getElementsByTagName("name")[0].childNodes[0].nodeValue;
	        var value = region.getElementsByTagName("Id")[0].childNodes[0].nodeValue;
	        Regions[postfix][i] = name;
	        RegionValues[postfix][i] = value;
	    }
	    num_regions[postfix] = regions.length;
	
	    var cities = xmlDom.getElementsByTagName("com.transcargo.geo.City");
	    for (i = 0; i < cities.length; i++) {
	        var city = cities[i];
	        name = city.getElementsByTagName("name")[0].childNodes[0].nodeValue;
	        value = city.getElementsByTagName("Id")[0].childNodes[0].nodeValue;
	        var reg_value = city.getElementsByTagName("Region__id")[0].childNodes[0].nodeValue;
	        Cities[postfix][i] = name;
	        CityValues[postfix][i] = value;
	        CityRegions[postfix][i] = reg_value;
	    }
	    num_cities[postfix] = cities.length;
    } else {
    	num_cities[postfix] = 0;
    	num_regions[postfix] = 0;
	    for (j = 0; j < s1.options.length; j++) {
	    	if (s1.options[j].value == 0) s1.options[j].text = '*';
	    }
    }
    
    if (num_regions[postfix] > 0) {
        s1.style.width = 140+'px';
        sr.style.width = 150+'px';
        sc.style.width = 150+'px';
        sc.style.visibility = s1.style.visibility;
        sr.style.visibility = s1.style.visibility;
        sr.style.position = 'static';
    } else {
        s1.style.width = 220+'px';
        sr.style.width = 0;
        sc.style.width = 220+'px';
        sc.style.visibility = s1.style.visibility;
        sr.style.visibility = s1.style.visibility;
        sr.style.position = 'absolute';
    }
    if (num_cities[postfix] == 0) {
        s1.style.width = 440+'px';
        sr.style.width = 0;
        sc.style.width = 0;
        sc.style.visibility = 'hidden';
        sr.style.visibility = 'hidden';

    }
    AddOption(sr, "любая обл.", "0");
    for (i = 0; i < num_regions[postfix]; i++) AddOption(sr, Regions[postfix][i], RegionValues[postfix][i]);

    AddOption(sc, "любой город", "0");
    for (i = 0; i < num_cities[postfix]; i++) AddOption(sc, Cities[postfix][i], CityValues[postfix][i]);

    if (doUpdateCountry[postfix] > 0) {
    	if (s1.value != doUpdateCountry[postfix]) {
    		s1.value = doUpdateCountry[postfix];
    		changeCountry(s1, false);
    	} else {
    		sr.value = doUpdateRegion[postfix];
    		changeRegion(sr, false);
    		sc.value = doUpdateCity[postfix];
    		doUpdateCountry[postfix] = 0;
    		doUpdateRegion[postfix] = 0;
    		doUpdateCity[postfix] = 0;
    	}
    }
}

function changeRegion(element, usreinit)
{
	var postfix = element.id;
	postfix=postfix.substr(6);
	if (isChanging) return;
    var sr = document.getElementById("Region" + postfix);
    var sc = document.getElementById("City" + postfix);
    var r = sr.value;
    sc.innerHTML='';
    AddOption( sc, "любой город", "0");
    for (var i = 0; i < num_cities[postfix]; i++) {
        if (r == 0 || (CityRegions[postfix][i] == r && r > 0)) AddOption( sc, Cities[postfix][i], CityValues[postfix][i]);
    }
    if (typeof onChangeRegion != 'undefined') onChangeRegion(postfix, usreinit);

}

function changeCity(element, usreinit)
{
	var postfix = element.id;
	postfix=postfix.substr(4);
    var sc = document.getElementById("City" + postfix);
    var cv = sc.value;
    for (var i = 0; i < CityValues[postfix].length; i++) {
    	if (CityValues[postfix][i] == sc.value) if (CityRegions[postfix][i] > 0) {
    	    var sr = document.getElementById("Region" + postfix);
    	    if (sr.value != CityRegions[postfix][i]) {
    	    	isChanging = true;
	    	    sr.value = CityRegions[postfix][i];
	    	    var r = sr.value;
	    	    sc.innerHTML='';
	    	    AddOption(sc, "любой город", "0");
	    	    for (var j = 0; j < num_cities[postfix]; j++) {
	    	        if (r == 0 || (CityRegions[postfix][j] == r && r > 0)) AddOption( sc, Cities[postfix][j], CityValues[postfix][j]);
	    	    }
	    	    sc.value = cv;
	    	    if (typeof onChangeRegion != 'undefined') onChangeRegion(postfix, usreinit);
	    	    isChanging = false;
    	    }
            break;
    	}
    }
    if (typeof onChangeCity != 'undefined') onChangeCity(postfix, usreinit);

}

function AddSearchArea(postfix, div, size)
{
	var ctr = 'Country' + postfix;
	var rgn = 'Region' + postfix;
	var cty = 'City' + postfix;
	var e = '<input name="' + postfix + '" id="' + postfix + '" size="' + size + '" onfocus="toggle(\'' + postfix + '\',true)" onblur="toggle(\'' + postfix + '\',false)" onChange="change(\'' + postfix + '\')" onkeyup="change(\'' + postfix + '\'); return true;">' + 
			'<input type="hidden" name="reg' + postfix + '" id="regFrom"><br>' +
			'<div style="position: absolute;visibility:hidden;z-index: 999;" id="' + postfix + '_Holder">' +
			'<table border="0" cellpadding="4" cellspacing="0" bgcolor="#AACCAA"><tr><td>' +
			'<table border="0" cellpadding="0" cellspacing="0">' +
			'<tr><td>' + 
			'<select tabIndex="-1" id="' + ctr + '" name="' + ctr + '" size="7" style="width: 440px"><option>Loading...</option></select>' + 
			'<select tabIndex="-1" id="' + rgn + '" name="' + rgn + '" size="7" style="width: 0px;visibility: hidden;"></select>' + 
			'<select tabIndex="-1" id="' + cty + '" name="' + cty + '" size="7" style="width: 0px;visibility: hidden;"></select>' + 
			'</td></tr>' +
			'</table></td></tr></table></div>';
	div.innerHTML = e;
	
	Regions[postfix] = new Array();
	RegionValues[postfix] = new Array();
	Cities[postfix] = new Array();
	CityValues[postfix] = new Array();
	CityRegions[postfix] = new Array();
	num_regions[postfix] = new Array();
	num_cities[postfix] = new Array();
	
	Areas[numAreas] = postfix;
	numAreas++;
}
function AddSearchAreaInitialized(postfix, div, size, cid, rid, ctid)
{
	AddSearchArea(postfix, div, size);
	
	doUpdateCountry[postfix] = cid;
	doUpdateRegion[postfix] = rid;
	doUpdateCity[postfix] = ctid;
}

function selectRegionElement(postfix, CountryID, RegionID, CityID) {
	var c =	document.getElementById("Country" + postfix);
	if (c.value == CountryID) {
		var sr = document.getElementById("Region" + postfix);
        sr.value = RegionID;
        changeRegion(sr, false);
        document.getElementById("City" + postfix).value = CityID;
	} else {
		c.value = CountryID;
		doUpdateCountry[postfix] = CountryID;
		doUpdateRegion[postfix] = RegionID;
		doUpdateCity[postfix] = CityID;
		changeCountry(c, false);
	}
}
